
function News() {

}

News.prototype.initUEditor = function () {
    window.ue = UE.getEditor('editor',{
        'initialFrameHeight':400,
        'serverUrl':'/ueditor/upload/'
    })
};

News.prototype.run = function () {
    var self = this;
    // self.listenUploadFileEvent();
    self.listenQiniuUploadFileEvent();
    self.initUEditor();
    self.listenSubmitBtn()
};

News.prototype.listenUploadFileEvent = function () {
    var uploadBtn = $("#thumbnail-btn");
    uploadBtn.change(function () {
        var file = uploadBtn[0].files[0];
        var formData = new FormData();
        // 这里的文件名一定要和后端传过来的文件名一样
        formData.append('file',file);
        xfzajax.post({
            'url':'/cms/upload_file/',
            'data':formData,
            // 告诉前端这个文件不需要处理
            'processData':false,
            'contentType':false,
            'success':function (result) {
                if (result['code']===200){
                    var url = result['data']['url'];
                    var thumbnailBtn = $("#thumbnail-form");
                    thumbnailBtn.val(url);
                }
            }
        })
    })
};

News.prototype.listenQiniuUploadFileEvent = function () {
    var self = this;
    var uploadBtn = $("#thumbnail-btn");
    uploadBtn.change(function () {
        var file = this.files[0];
        xfzajax.get({
            'url':'/cms/qntoken/',
            'success':function (result) {
                if(result['code']===200){
                    // 获取后端传过来的data里面的token值
                    var token = result['data']['token'];
                    // 总体效果是生成一个带后缀的文件名，如20190122.jpg，前面是获取当前时间作为名字，后面是拼接后缀（jpg,png等)
                    // pip是删除数组中最后一位数，同时返回最后一位，这样不管视频文件名字里有多少个点，都可以去到后缀名
                    var key = (new Date()).getTime() + '.' + (file.name.split('.')).pop();
                    var putExtra = {
                        fname:key,
                        params:{},
                        // 设置可以上传的文件格式
                        mimeType:['image/jpeg','image/png','image/gif','video/x-ms-wmv']
                    };
                    var config = {
                        useCdnDomain:true,
                        // 设置重试次数
                        retryCount:6,
                        // 指定存储片区,z2代表华南
                        region:qiniu.region.z2
                    };
                    var observable = qiniu.upload(file,key,token,putExtra,config);
                    observable.subscribe({
                        'next':self.handleFileUploadEvent,
                        'error':self.handleFileUploadError,
                        'complete':self.handleFileUploadComtlete
                    })
                }
            }
        })
    })
};

News.prototype.handleFileUploadEvent = function (response) {
    var total = response.total;
    var percentFloat = total.percent;
    var percent = parseFloat(percentFloat);
    var percentText = percent.toFixed(0) + '%';
    var progressGroup = News.progressGroup;
    var progressBar = $(".progress-bar");
    if(percent >= 0){
        progressBar.css({'width':0});
        progressBar.text('0%');
        // toFixed(0)可以去掉小数后面的数
        progressGroup.show();
        progressBar.css({'width':percentText});
        progressBar.text(percentText);
    }
};

News.prototype.handleFileUploadError = function (error) {
    window.messageBox.showError(error.message);
    var progressGroup = $("#progress-group");
    progressGroup.hide();
    console.log(error.message);
};

News.prototype.handleFileUploadComtlete = function (response) {
      var progressGroup = $("#progress-group");
      progressGroup.hide();
      // 获取默认地址
      var domain = 'http://plrq84agi.bkt.clouddn.com/';
      // 获取文件名
      var fileName = response.key;
      var url = domain + fileName;
      // 将上传好的文件地址保存到输入框中
      var thumbnailInput = $("input[name='thumbnail']");
      thumbnailInput.val(url);
};

News.prototype.listenSubmitBtn = function () {
    var submitBtn = $("#submit-btn");
    submitBtn.click(function (event) {
        // 取消默认点击事件
        event.preventDefault();
        var btn = $(this);
        var pk = btn.attr('data-news-id');
        var title = $("input[name='title']").val();
        var category = $("select[name='category']").val();
        var desc = $('input[name="desc"]').val();
        var thumbnail = $("input[name='thumbnail']").val();
        var content = window.ue.getContent();
        var url = '';
        if(pk){
            url = '/cms/edit_news/'
        }else {
            url = '/cms/write_news/'
        }
        xfzajax.post({
            'url':'/cms/write_news/',
            'data':{
                'title':title,
                'category':category,
                'desc':desc,
                'thumbnail':thumbnail,
                'content':content,
                "pk":pk
            },
            'success':function (result) {
                if(result['code']===200){
                    xfzalert.alertSuccess('恭喜您，新闻发表成功！',function () {
                        window.location.reload();
                    })
                }
            }
        })

    })
};

$(function () {
   news = new News();
   news.run();

   News.progressGroup = $("#progress-group");
});